package com.bwie.policy;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.bwie.pojo.TbPacketRecord;
import com.bwie.pojo.TbPolicy;
import com.bwie.utils.Result;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;

import java.util.Date;

public class DayRedPacketPolicy implements IRedPolicy{
    private TbPolicy tbPolicy;
    private Integer userId;
    private KafkaTemplate kafkaTemplate;
    private StringRedisTemplate redisTemplate;


    public DayRedPacketPolicy(TbPolicy tbPolicy, Integer userId, KafkaTemplate kafkaTemplate, StringRedisTemplate redisTemplate) {

        System.out.println("天次触发策略");
        this.tbPolicy = tbPolicy;
        this.userId = userId;
        this.kafkaTemplate = kafkaTemplate;
        this.redisTemplate = redisTemplate;

    }


    @Override
    public Result execute() {
        //判断是否可以抢红包抢的次数
        String key = "red-" + tbPolicy.getPolicyId() + "-" + userId;
        Boolean hasKey = redisTemplate.hasKey(key);
        if (!hasKey) {
            //如果key不存在则从来没有抢过红包
            redisTemplate.opsForValue().set(key, String.valueOf(tbPolicy.getTopLimit()));
        }
        Long decrement = redisTemplate.opsForValue().decrement(key);
        if (decrement < 0) {
            return Result.error().setMsg("红包已经抢完了");
        }

        long time = new Date().getTime();
        if (time < tbPolicy.getBeginTime().getTime()) {
            return Result.error().setMsg("红包活动未开始");
        }
        if (time > tbPolicy.getEndTime().getTime()) {
            return Result.error().setMsg("红包活动已结束");
        }
        double amount = RandomUtil.randomDouble(0.01, tbPolicy.getPacketAmount());
        TbPacketRecord tbPacketRecord = new TbPacketRecord();
        tbPacketRecord.setUserId(userId);
        tbPacketRecord.setPacketAmount(amount);
        tbPacketRecord.setPolicyId(tbPolicy.getPolicyId());
        //消息不重复
        long nextId = IdUtil.getSnowflake(1, 1).nextId();
        tbPacketRecord.setMsgId(nextId);
        redisTemplate.opsForValue().set("msg-"+nextId,"1");
        String message = JSON.toJSONString(tbPacketRecord);
        kafkaTemplate.send("topic-packet", message);
        return Result.ok().setData(amount);
    }
}
